// pages/users/bindmobile/index.js

const commonUser = require('../../../common/commonUser.js');
const customRequst = require('../../../common/customRequst');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    mobile:'',
    yzm:'',
    token:'',
    code:0,
    yzm_tips:'获取短信验证码',
    redirce_url:'',
    openid: ''
  },

  onLoad: function (options) {
    let that = this
    console.log(options.openid)
    that.setData({
      openid: options.openid
    })
    //加载表单提交token
    customRequst.postRequest('api/common/get_form_token').then(res => {
      that.setData({
        formToken: res.data.token
      })
    })
    //获取前一个页面传递的参数

  },

  onShow: function () {

  },


  bindPhoneInput: function (e) {
    console.log(e.detail.value)
    this.setData({
      phone: e.detail.value
    });
  },

  bindCodeInput: function (e) {
    console.log(e.detail.value)
    this.setData({
      yzm: e.detail.value
    });
  },


/** 
   * 点击获取短信验证码
   */
  onClickCheckCode: function (e) {
    let that = this
    let time = 59
    // 判断手机号格式是否正确
    if (this.data.phone.length == 0) {
      wx.showToast({
        title: '请填写手机号码',
        icon: 'none'
      })
      return
    }
    let reg = /^(1[3|4|5|6|7|8|9])\d{9}$/;
    if (!reg.test(this.data.phone)) {
      wx.showToast({
        title: '手机格式错误',
        icon: 'none'
      })
      return
    }
  
    //发送请求
    customRequst.postRequest('common/getyzm', {
      mobile: that.data.phone,
      event: 'bindmobile'
    }).then(res => {
      // 开启定时器
      let timer = setInterval(function () {
        // 判断剩余秒数
        if (time == 0) {
          // 清除定时器和复原按钮
          clearInterval(timer);
          that.setData({
            yzm_tips: '重新获取验证码'
          })
        } else {
          that.setData({
            yzm_tips: time + '秒'
          })
          time--;
        }
      }, 1000);
    })
  },

  //数据提交
  onClickSubmit:function () {
    let that = this;
    let submitData={
      mobile:that.data.phone,
      yzm:that.data.yzm,
      openid: that.data.openid,
      token:that.data.formToken
    };
    customRequst.postRequest('api/user/bindmobile',submitData).then(res => {
      if(res.code == 1){

        //缓存数据
        commonUser.setUserInfo(res.data);

        //跳转到之前请求页面
        wx.showToast({
          title:'绑定手机号成功',
          success: function() {
            wx.switchTab({
              url: '/pages/index/index',
            });
          }
        })
      }else{
        wx.showToast({
          title:res.msg,
        })
        that.setData({
          token: res.data.token
        })
      }
    })
  }

})